﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using JohnnySins.DAL;
using JohnnySins.DAL.Repositories;
using JohnnySins.Entities;
using JohnnySins.Code;

namespace JohnnySins.Admin
{
    public partial class FileUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string qqfile = Request["qqfile"];
            int photoSetId = Convert.ToInt32(Request["photoSetId"]);
            string path = Server.MapPath("~/Files/PhotoSets/" + photoSetId.ToString() + "/");
            string file = string.Empty;

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            try
            {
                var stream = Request.InputStream;
                if (String.IsNullOrEmpty(Request["qqfile"]))
                {
                    // IE
                    HttpPostedFile postedFile = Request.Files[0];
                    stream = postedFile.InputStream;
                    //file = Path.Combine(path, Path.GetFileName(Request.Files[0].FileName));
                    qqfile = Request.Files[0].FileName;
                }
                else
                {
                    //Webkit, Mozilla
                    //file = Path.Combine(path, qqfile);
                }

                using (var repo = RepositoryFactory.ResolveRepository<PhotoSetRepository>())
                {
                    PhotoSetPhoto itm = new PhotoSetPhoto();
                    itm.PhotoSetId = photoSetId;
                    itm.PhotoSetPhotoFileName = qqfile;
                    repo.InsertPhoto(itm);
                    file = Path.Combine(path, Path.GetFileName(itm.PhysFileName));
                }
                
                var buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                File.WriteAllBytes(file, buffer);

            }
            catch (Exception ex)
            {
                ReturnResult(false, ex.Message);
            }

            ReturnResult(true, "");
        }

        public void ReturnResult(bool result, string message)
        {
            string json = "";
            if (result)
                json = "{\"success\":\"true\"}";
            else
                json = "[{\"success\":false},{\"message\":\"" + message + "\"}]";
            Response.Clear();
            //Response.ContentType = "application/json; charset=utf-8";
            Response.ContentType = "text/html";
            Response.Write(json);
            Response.End();
        }
    }
}